<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\alibaba;
/*
    阿里短信接口插件
    调用：
        $AliSms=new \app\extend\alibaba\AliSms;
        $AliSms->SendSms('13477191977','SMS_192535206',"{'code':'123456'}");
*/
use \app\base\Common;
class AliSms extends Common
{
    private $API_URL="https://dysmsapi.aliyuncs.com/";
    private $AccessKeyId="LTAI4G1wRUkGdk5cNxfKPwh1";
    private $AccessKeySecret="C1hvx7yIU4uSUpAtRJt8WQHanY3Fsf";
    private $SignName="芒果户外俱乐部";

	protected function _initialize()
	{
    	//执行父类的构造方法
    	parent::_initialize();
    }
    public function SendSms($mobile,$Code,$Param="{'code':'123456'}")
    {
        $SignatureNonce=GetRandStr(24);
        //获取UTC时间
        $Timestamp=gmdate("Y-m-d\TH:i:s\Z");

        //构造公共参数
        $data=[
            'AccessKeyId'=>$this->AccessKeyId,
            'Format'=>'json',
            'RegionId'=>'cn-hangzhou',
            'SignatureMethod'=>'HMAC-SHA1',
            'SignatureNonce'=>$SignatureNonce,
            'Timestamp'=>$Timestamp,
            'Version'=>'2017-05-25',
            'SignatureVersion'=>'1.0',
        ];

        //生成业务参数
        $data['Action']='SendSms';
        $data['PhoneNumbers']=$mobile;
        $data['SignName']=$this->SignName;
        $data['TemplateCode']=$Code;
        $data['TemplateParam']=$Param;

        //生成签名信息
        $data['Signature']=$this->Sign($data,$this->AccessKeySecret);
        $result=\json_decode(Post_Curl($data,$this->API_URL),true);
        WLog('AliSmsLog','请求：'.array2string($data));
        WLog('AliSmsLog','响应：'.array2string($result));
        if($result['Message']=='OK'){
            return Result(0,'发送成功');
        }else{
            return Result(1,$result['Message']);
        }
    }
    //hash_hmac签名
    private function Sign($parameters, $accessKeySecret)
    {
        //将参数Key按字典顺序排序
        ksort($parameters);
        //生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach($parameters as $key => $value)
        {
            $canonicalizedQueryString .= '&' . $this->Encode($key). '=' . $this->Encode($value);
        }
        //生成用于计算签名的字符串 stringToSign
        $stringToSign = 'POST&%2F&' . $this->Encode(substr($canonicalizedQueryString, 1));
        //计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
        return $signature;
    }
    //URL编码
    private function Encode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }
}
?>